package com.warski.wonderfires.media;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.util.Base64;
import android.util.Log;

import com.warski.wonderfires.dlna.DLNAManager;
import com.warski.wonderfires.dlna.listener.DLNAControlListener;
import com.warski.wonderfires.dlna.model.MediaInfo;
import com.warski.wonderfires.dlna.type.EnumMediaType;
import com.warski.wonderfires.model.MusicItemInfo;
import com.warski.wonderfires.model.SongListItemInfo;
import com.warski.wonderfires.page.music.MusicFragment;
import com.warski.wonderfires.utils.BasicUtils;
import com.warski.wonderfires.utils.FileUtils;
import com.warski.wonderfires.utils.Logger;
import org.fourthline.cling.model.action.ActionInvocation;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuhaiping on 2020/8/30.
 * 实现音乐播放，同时包装了dlna，内部决定是手机播放还是发送到其他设备播放
 */
public class MusicPlayer {
    public static long getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    public interface MusicPlayerListener {
        void onMusicChanged();
        void onGetPosition(int msec);
    }

    public enum PlayModeType {
        Normal,//循环
        Random,//随机
        ;
    }

    private static MediaPlayer mediaPlayer = null;
    private static PlayModeType mode = PlayModeType.Normal;
    private static SongListItemInfo currentSongList = null;
    private static int currentMusicIndex;
    private static List<MusicItemInfo> musicList;
    private static MusicPlayerListener listener;
    private static boolean dlnaRunning = false;
    private static boolean isPlaying = false;
    private static int position = 0;
    public static MusicPlayerListener getListener() {
        return listener;
    }

    public static void setListener(MusicPlayerListener listener) {
        MusicPlayer.listener = listener;
    }

    /**
     * 初始化
     */
    private static void init() {
        mediaPlayer = new MediaPlayer();

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(isPlaying) {
                    playNext();
                }
            }
        });
    }

    private static void setLrc(int index){
        MusicItemInfo musicItemInfo = currentSongList.getMusicList().get(index);
        String lrc = musicItemInfo.getLrc();
        if (!lrc.isEmpty()){
            InputStream inputStream = FileUtils.readAssetAsInputStream(lrc);
            MusicFragment.setMusicLrc(inputStream);
        }else {
            MusicFragment.setMusicLrc(null);
        }
    }
    /**
     * 获取播放模式
     *
     * @return
     */
    public static PlayModeType getMode() {
        return mode;
    }

    /**
     * 设置播放模式
     *
     * @param mode
     */
    public static void setMode(PlayModeType mode) {
        MusicPlayer.mode = mode;
        if (currentSongList == null) return;
        if (mode == PlayModeType.Normal) {
            //顺序播放
            musicList = new ArrayList<>(currentSongList.getMusicList());
        } else if (mode == PlayModeType.Random) {
            //随机排序
            //生成一个随机数，然后将列表中的两项交换位置
            musicList = new ArrayList<>(currentSongList.getMusicList());
            int count = currentSongList.getMusicList().size();
            while (count > 0) {
                int p1 = BasicUtils.getRandom(0, currentSongList.getMusicList().size() - 1);
                int p2 = BasicUtils.getRandom(0, currentSongList.getMusicList().size() - 1);
                MusicItemInfo temp = musicList.get(p1);
                musicList.set(p1, musicList.get(p2));
                musicList.set(p2, temp);
                count--;
            }
        }
        play(currentMusicIndex);
    }

    /**
     * 获取当前歌单
     *
     * @return
     */
    public static SongListItemInfo getCurrentSongList() {
        return currentSongList;
    }

    /**
     * 获取当前播放音乐索引
     *
     * @return
     */
    public static int getCurrentMusicIndex() {
        return currentMusicIndex;
    }

    public static void setCurrentMusicIndex(int index) {
        currentMusicIndex = index;
    }

    /**
     * 获取当前播放音乐
     *
     * @return
     */
    public static MusicItemInfo getCurrentMusic() {
        if (musicList == null) return null;
        return musicList.get(currentMusicIndex);
    }

    /**
     * 当前播放列表
     *
     * @return
     */
    public static List<MusicItemInfo> getMusicList() {
        return musicList;
    }


    /**
     * 获取歌曲长度
     *
     * @return
     */
    public static int getLength() {
        if (mediaPlayer != null) {
            return mediaPlayer.getDuration();
        }
        return 0;
    }

    /**
     * 获取当前播放位置 毫秒
     * 通过回调返回
     * @return
     */
    public static void queryPosition() {
        if(dlnaRunning){
            DLNAManager.getPosition(new DLNAControlListener(){
                public void onDLNASuccess(ActionInvocation invocation){

                }

                public void onDLNAMessage(ActionInvocation invocation, Object... message){
                    //message[0]当前秒
                    //message[1]是否结束
                    if((boolean)message[1] == true && position != 0){
                        playNext();
                    }
                    else if(listener != null){
                        position = (int)message[0] * 1000;
                        listener.onGetPosition(position);
                    }
                }

                public void onDLNAError(ActionInvocation invocation, String error){

                }
            });
        }
        else if (mediaPlayer != null) {
            position = mediaPlayer.getCurrentPosition();
            if(listener != null){
                listener.onGetPosition(position);
            }
        }
    }

    /**
     * 播放歌单
     *
     * @param songList
     * @return
     */
    public static boolean play(SongListItemInfo songList) {
        if (currentSongList != null && currentSongList.getTitle().compareTo(songList.getTitle()) == 0) {
            //同样歌单不处理
            setMode(mode);
            return true;
        }
        currentSongList = songList;
        if (currentSongList.getMusicList().size() == 0) {
            Logger.error("空歌单: %s", currentSongList.getTitle());
            return false;
        }
        if (mediaPlayer == null) {
            init();
        }
        //初始化歌曲列表并开始播放
        setMode(mode);
        return true;
    }

    /**
     * 播放上一首
     *
     * @return
     */
    public static void playPrev() {
        if (currentMusicIndex == 0) {
            currentMusicIndex = musicList.size() - 1;
        } else {
            currentMusicIndex--;
        }
        play(currentMusicIndex);
        setLrc(currentMusicIndex);
    }

    /**
     * 播放下一首
     *
     * @return
     */
    public static void playNext() {
        if (currentMusicIndex == musicList.size() - 1) {
            currentMusicIndex = 0;
        } else {
            currentMusicIndex++;
        }
        play(currentMusicIndex);
        setLrc(currentMusicIndex);
    }

    /**
     * 重新播放
     * @return
     */
    public static void replay() {
        stop();
        play(currentMusicIndex);
    }

    /**
     * 播放歌单中指定的音乐
     *
     * @param musicIndex
     * @return
     */
    private static void play(int musicIndex) {
        try {
            currentMusicIndex = musicIndex;
            MusicItemInfo musicInfo = musicList.get(musicIndex);

            if (dlnaRunning) {
                DLNAManager.play(musicInfo2MediaInfo(musicInfo), new DLNAControlListener() {
                    public void onDLNASuccess(ActionInvocation invocation) {

                    }

                    public void onDLNAMessage(ActionInvocation invocation, Object... message) {

                    }

                    public void onDLNAError(ActionInvocation invocation, String error) {
                        /*Log.d("TAG", "onDLNAError:" + musicIndex);
                        stop();
                        play(musicIndex);*/
                    }
                });
            } else {
                mediaPlayer.reset();
                if (FileUtils.isAssetFile(musicInfo.getUrl())) {
                    AssetFileDescriptor assetFile = FileUtils.readAssetAsFD(musicInfo.getUrl());
                    mediaPlayer.setDataSource(assetFile.getFileDescriptor(), assetFile.getStartOffset(), assetFile.getLength());
                }
                mediaPlayer.prepare();
                mediaPlayer.start();
            }

            isPlaying = true;
            if (listener != null) {
                listener.onMusicChanged();
            }
        } catch (Exception e) {
            Logger.error(e);
        }
    }

    /**
     * 继续播放
     *
     * @return
     */
    public static void play() {
        isPlaying = true;
        if(dlnaRunning){
            DLNAManager.play(null);
        }
        else if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    /**
     * 暂停播放
     *
     * @return
     */
    public static void pause() {
        isPlaying = false;
        if(dlnaRunning){
            DLNAManager.pause(null);
        }
        else if (mediaPlayer != null) {
            mediaPlayer.pause();
        }
    }

    /**
     * 停止播放
     *
     * @return
     */
    public static void stop() {
        isPlaying = false;
        //两种模式的stop都调用
        if(dlnaRunning){
            DLNAManager.stop(null);
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    /**
     * 播放指定位置
     *
     * @param msec
     * @return
     */
    public static void seekTo(int msec) {
        if(dlnaRunning){
            DLNAManager.seekTo(msec / 1000, null);
        }
        else if (mediaPlayer != null) {
            mediaPlayer.seekTo(msec);
        }
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    public static boolean isPlaying() {
        return isPlaying;
    }

    /**
     * 将音乐转化为dlna媒体对象
     *
     * @param musicInfo
     * @return
     */
    private static MediaInfo musicInfo2MediaInfo(MusicItemInfo musicInfo) {
        MediaInfo mediaInfo = new MediaInfo();
        mediaInfo.setMediaType(EnumMediaType.TYPE_AUDIO);
        mediaInfo.setMediaName(musicInfo.getName());
        mediaInfo.setUrl(musicInfo.getUrl());
        mediaInfo.setMediaId(Base64.encodeToString(musicInfo.getUrl().getBytes(), Base64.NO_WRAP));
        return mediaInfo;
    }

    /**
     * 判断当前dlna是否可用
     *
     * @return
     */
    public static boolean isDlnaAvailable() {
        return DLNAManager.getConnectedDevice() != null;
    }

    /**
     * 开启dlna
     */
    public static void startDlna() {
        dlnaRunning = true;
        position = 0;
//        replay();
    }

    /**
     * 关闭dlna
     */
    public static void stopDlna() {
        dlnaRunning = false;
        DLNAManager.stop(null);
    }

    /**
     * dlna运行中
     *
     * @return
     */
    public static boolean isDlnaRunning() {
        return dlnaRunning;
    }
}
